package com.geekaca.news.service.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.db.PageResult;
import com.geekaca.news.domain.News;
import com.geekaca.news.domain.NewsCategory;
import com.geekaca.news.domain.NewsTag;
import com.geekaca.news.domain.NewsTagRelation;
import com.geekaca.news.mapper.NewsCategoryMapper;
import com.geekaca.news.mapper.NewsMapper;
import com.geekaca.news.mapper.NewsTagMapper;
import com.geekaca.news.mapper.NewsTagRelationMapper;
import com.geekaca.news.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Transactional
@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private NewsCategoryMapper categoryMapper;
    @Autowired
    private NewsTagMapper tagMapper;
    @Autowired
    private NewsTagRelationMapper tagRelationMapper;


    public List<News> selectNewsAndCategory() {
        List<News> newsList = newsMapper.selectNewsAndCategory();
        return newsList;
    }

    @Override
    public List<News> getAllNews() {
        return newsMapper.selectNewsAndCategory();
    }

    @Override
    public News selectNewsAndCommentById(Long id) {
        News news = newsMapper.selectNewsAndCommentById(id);
        return news;
    }

    @Override
    public News getById(Long newsID) {
        News news = newsMapper.selectNewsAndCommentById(newsID);
        return news;
    }

    @Override
    public List<News> blurSearchByTitleContent(News news) {
        List<News> newsList = newsMapper.blurSearchByTitleContent(news);
        return newsList;

    }

    @Override
    public Integer getTotalNews() {
        return newsMapper.getAllNewsCount("");
    }

    @Override
    public Integer getAllNewsCount(String keyword) {
        return newsMapper.getAllNewsCount(keyword);
    }

    @Override
    public List<News> getAllNews(int page, int limit, String keyword) {
        int start = (page - 1) * limit;
        int pageSize = limit;
        List<News> allNews = newsMapper.getAllNews(start, pageSize, keyword);
        return allNews;
    }

    @Override
    public List<News> getAllNewsByCategory(int page, int limit, String category) {
        int start = (page - 1) * limit;
        int pageSize = limit;
        return newsMapper.getAllNewsByCategory(start, pageSize, category);
    }

    @Override
    public List<News> selectAllNewsByTagId(Integer tagId, Integer pageNum) {
        Integer pageSize = 3;
        Integer start = (pageNum-1)*pageSize;
        return newsMapper.selectAllNewsByTagId(tagId,start,pageSize);
    }

    @Override
    public int selectAllNewsByTagIdCount(Integer tagId) {
//        Integer pageSize =2;
//        Integer start = (pageNum-1)*pageSize;
//        return newsMapper.getNewsTagIdCount(start, pageSize, tagId);
        return  newsMapper.getNewsTagIdCount(tagId);
    }

    @Override
    public PageResult getNewsPage(PageUtil pageUtil) {
        return null;
    }

    @Override
    public int addNews(News blog) {
        /**
         * 1, 向新闻表增加一条数据
         * 2, 向新闻和标签关联表 插入数据
         *  循环每一个标签，插入关联表
         */

        NewsCategory blogCategory = categoryMapper.selectByPrimaryKey((long) blog.getNewsCategoryId());
        if (blogCategory == null) {
            blog.setNewsCategoryId(0);
            blog.setNewsCategoryName("默认分类");
        } else {
            blog.setNewsCategoryName(blogCategory.getCategoryName());
            blogCategory.setCategoryRank(blogCategory.getCategoryRank() + 1);
        }
        blog.setIsDeleted(0);
        int inserted = newsMapper.insertSelective(blog);
        if(inserted<1){
            return 0;
        }

        List<NewsTag> allTags = tagMapper.getAllTags(null, null);
        HashMap<String, Integer> tagMap = new HashMap<>();
        for (NewsTag tag : allTags) {
            tagMap.put(tag.getTagName(),tag.getTagId());
        }
        // 获取所有标签
        String newsTags = blog.getNewsTags();
        String[] tagNames = newsTags.split(",");
        for (int i = 0; i < tagNames.length; i++) {
            String tagName = tagNames[i];
            Integer tagId = tagMap.get(tagName);
            if(tagId==null){
                // tag 不存在，则新建tag
                NewsTag newsTag = new NewsTag();
                newsTag.setTagName(tagName);
                tagMapper.insertSelective(newsTag);
                tagId= newsTag.getTagId();
            }
            NewsTagRelation tagRelation = new NewsTagRelation();
            tagRelation.setNewsId(blog.getNewsId());
            tagRelation.setTagId(tagId);
            inserted = tagRelationMapper.insertSelective(tagRelation);
        }
        return inserted;
    }

    @Override
    public int updateNews(News blog) {
        NewsCategory blogCategory = categoryMapper.selectByPrimaryKey((long) blog.getNewsCategoryId());
        if (blogCategory == null) {
            blog.setNewsCategoryId(0);
            blog.setNewsCategoryName("默认分类");
        } else {
            blog.setNewsCategoryName(blogCategory.getCategoryName());
//            blogCategory.setCategoryRank(blogCategory.getCategoryRank() + 1);
        }
        blog.setIsDeleted(0);
        int affected= newsMapper.updateByPrimaryKey(blog);

        if(affected<1){
            return affected;
        }

        List<NewsTag> allTags = tagMapper.getAllTags(null, null);
        HashMap<String, Integer> tagMap = new HashMap<>();
        for (NewsTag tag : allTags) {
            tagMap.put(tag.getTagName(),tag.getTagId());
        }
        // 获取所有标签
        String newsTags = blog.getNewsTags();
        String[] tagNames = newsTags.split(",");
        for (int i = 0; i < tagNames.length; i++) {
            String tagName = tagNames[i];
            Integer tagId = tagMap.get(tagName);
            if(tagId==null){
                // tag 不存在，则新建tag
                NewsTag newsTag = new NewsTag();
                newsTag.setTagName(tagName);
                tagMapper.insertSelective(newsTag);
                tagId= newsTag.getTagId();
            }
            NewsTagRelation tagRelation = new NewsTagRelation();
            tagRelation.setNewsId(blog.getNewsId());
            tagRelation.setTagId(tagId);
            affected = tagRelationMapper.insertSelective(tagRelation);
        }
        return affected;
    }

    @Override
    public int deleteNews(List<Long> ids) {
        int affected = newsMapper.deleteByPrimaryKey(ids);
        // 查询关联表数据



        return affected;
    }

    public int updateNewsViews(Long newsId) {
        return newsMapper.increateViews(newsId);

    }

    @Override
    public List<NewsTag> getHottags() {
        return newsMapper.getHotTags();
    }

    @Override
    public List<News> getHotNews() {
        return newsMapper.getHotNews();
    }

    @Override
    public List<News> getRecentNews() {
        return newsMapper.getRecentNews();
    }

    @Override
    public int getNewsCountByCatgeory(String keyword) {
        return newsMapper.getNewsCountByCate(keyword);
    }
}
